import {
  Button,
  Col,
  Layout,
  List,
  message,
  Modal,
  Row,
  Table,
  Typography,
  Upload,
} from "antd";
import {
  DeleteOutlined,
  DownloadOutlined,
  InboxOutlined,
  UploadOutlined,
} from "@ant-design/icons";
import React, { useCallback, useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { createSeaBidForTender } from "../../api/tendering/uploadApi";
import {
  fetchSeaSummaryFile,
  downloadSeaSummaryFile,
  createSeaSummary,
} from "../../api/tendering/summaryApi";
import { getBidsForTender } from "../../api/tendering/tenderApi";
import * as XLSX from "xlsx";
import type { BidRecord } from "../../components/BidRecordList/schema";
import type { BidInfo } from "../../types/api";
import FileUploader from "../../components/FileUploader/FileUploader";
import BidRecordList from "../../components/BidRecordList/BidRecordList";

const { Content } = Layout;
const { Title } = Typography;

const SummaryForSeaTransportation: React.FC = () => {
  const navigate = useNavigate();
  const { tableId } = useParams<{ tableId: string }>();


  const [bidRecords, setBidRecords] = useState<BidRecord[]>([]);
  const [uploading, setUploading] = useState(false);

  const [excelData, setExcelData] = useState([]);
  const [excelColumns, setExcelColumns] = useState([]);


  const fileInputRefs = React.useRef({});

  const fetchBidRecords = useCallback(async () => {
    try {
      const records = await getBidsForTender(tableId!);
      setBidRecords(
        records.bids.map(
          (bid: BidInfo): BidRecord => ({
            id: bid.id,
            name: bid.name,
            has_bargaining: bid.has_bargaining,
          })
        )
      );
    } catch (err) {
      message.error("加载投标记录失败");
    }
  }, [tableId]);

  useEffect(() => {
    fetchBidRecords();
  }, [fetchBidRecords]);

  // 解析并展示汇总Excel
  const fetchAndParseSummary = async () => {
    try {
      if (!tableId) {
        message.error(
          "未找到tableId，无法获取汇总文件，请返回上一页重新进入页面。"
        );
        return;
      }
      const res = await fetchSeaSummaryFile(tableId);
      const arrayBuffer = await res.blob.arrayBuffer();
      const workbook = XLSX.read(arrayBuffer, { type: "array" });
      const sheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[sheetName];
      const jsonData = XLSX.utils.sheet_to_json(worksheet, {
        header: 1,
        defval: "",
      });
      // 处理自定义结构：
      // 第一行A1为标题，第二行为分组表头，第三行为表头，第四行起为数据
      if (jsonData.length >= 4) {
        const maxCol = 20;
        const groupRow = jsonData[1].slice(0, maxCol); // 第二行
        const titleRow = jsonData[2].slice(0, maxCol); // 第三行
        const mainTitle = jsonData[0][0] || "";
        const columns = [];
        // A-F列（0-5）固定为公共产品信息
        const publicChildren = [];
        for (let k = 0; k < 6; k++) {
          publicChildren.push({
            title: titleRow[k],
            dataIndex: `col${k}`,
            key: `col${k}`,
            width: 180,
            ellipsis: false,
            onHeaderCell: () => ({
              style: {
                maxWidth: 180,
                whiteSpace: "normal",
                wordBreak: "break-all",
                textAlign: "center",
              },
            }),
            render: (text) => (
              <div style={{ whiteSpace: "pre-wrap", wordBreak: "break-all" }}>
                {text}
              </div>
            ),
          });
        }
        columns.push({
          title: mainTitle,
          children: publicChildren,
        });
        // G列（6）及以后，按每4列分组
        let i = 6;
        while (i < maxCol) {
          let groupTitle = groupRow[i];
          if (!groupTitle) {
            groupTitle = mainTitle;
          }
          const start = i;
          let end = Math.min(i + 4, maxCol);
          for (let j = i + 1; j < end; j++) {
            if (groupRow[j]) {
              end = j;
              break;
            }
          }
          const children = [];
          for (let k = start; k < end; k++) {
            children.push({
              title: titleRow[k],
              dataIndex: `col${k}`,
              key: `col${k}`,
              width: 180,
              ellipsis: false,
              onHeaderCell: () => ({
                style: {
                  maxWidth: 180,
                  whiteSpace: "normal",
                  wordBreak: "break-all",
                  textAlign: "center",
                },
              }),
              render: (text) => (
                <div style={{ whiteSpace: "pre-wrap", wordBreak: "break-all" }}>
                  {text}
                </div>
              ),
            });
          }
          columns.push({
            title: groupTitle,
            children,
          });
          i = end;
        }
        // 只取前10行数据，且每行只取前20列
        const dataSource = jsonData.slice(3, 13).map((row, i) => {
          const obj = { key: i };
          row.slice(0, maxCol).forEach((cell, idx) => {
            obj[`col${idx}`] = cell;
          });
          return obj;
        });
        setExcelColumns(columns);
        setExcelData(dataSource);
      } else {
        setExcelColumns([]);
        setExcelData([]);
      }
    } catch (err) {
      message.error("解析汇总文件失败");
    }
  };

  useEffect(() => {
    fetchAndParseSummary();
  }, [tableId]);

  async function handleUpload(file: File, startingPort: string) {
    try {
      await createSeaBidForTender(tableId!, startingPort, file);
      message.success("上传成功");
    } catch (err) {
      message.error("上传失败");
    }
  }

  async function handleSummary() {
    try {
      await createSeaSummary(tableId!);
      message.success("汇总成功");
    } catch (err) {
      message.error("汇总失败");
    }
  }

  async function handleDownload() {
    try {
      await downloadSeaSummaryFile(tableId!);
    } catch (err) {
      message.error("下载失败");
    }
  }

  return (
    <Layout style={{ height: "90vh", width: "96vw" }}>
      <Content style={{ height: "100%", width: "100%", display: "flex" }}>
        <Row
          gutter={[0, 0]}
          style={{
            height: "100%",
            width: "100%",
            display: "flex",
            flexWrap: "nowrap",
          }}
        >
          {/* 左侧上传区域 */}
          <Col
            span={8}
            style={{
              border: "16px",
              boxSizing: "border-box",
              background: "#fff",
              marginRight: 8,
              minWidth: "320px",
              height: "100%",
              position: "sticky",
              overflow: "hidden",
              zIndex: 2,
              display: "flex",
              flexDirection: "column",
              padding: "0 16px 0 16px",
            }}
          >
            <div
              style={{
                padding: "8px",
                display: "flex",
                flexDirection: "column",
                height: "100%",
                width: "100%",
                overflow: "hidden",
              }}
            >
              <Button
                style={{ marginBottom: 16, width: "110px" }}
                onClick={() => navigate("/")}
              >
                返回上一页
              </Button>

              <FileUploader
                title="海运投标上传（上海）"
                onUpload={(file) => handleUpload(file, "Shanghai")}
              />

              <FileUploader
                title="海运投标上传（九江）"
                onUpload={(file) => handleUpload(file, "Jiujiang")}
              />

              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  flex: 1,
                  minHeight: 0,
                  marginTop: "16px",
                }}
              >
              <BidRecordList
                bidRecords={bidRecords}
                onUploading={setUploading}
              ></BidRecordList>
                <Button
                  type="primary"
                  onClick={handleSummary}
                  loading={uploading}
                  style={{ marginRight: "16px", marginBottom: "8px" }}
                >
                  {uploading ? "处理中..." : "汇总"}
                </Button>
              </div>
            </div>
          </Col>

          {/* 右侧预览区域 */}
          <Col
            span={16}
            style={{
              border: "16px",
              height: "100%",
              overflow: "hidden",
              flex: "1 1 0%",
            }}
          >
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                height: "100%",
                width: "100%",
                border: "16px",
                boxSizing: "border-box",
                background: "#fff",
                margin: 0,
                padding: "16px",
                overflow: "hidden",
              }}
            >
              {excelColumns.length === 0 ? (
                <div
                  style={{
                    color: "#faad14",
                    fontWeight: 500,
                    fontSize: 18,
                    textAlign: "center",
                    marginTop: 40,
                  }}
                >
                  暂无汇总数据，请先上传文件或点击“汇总”按钮生成。
                </div>
              ) : (
                <>
                  <div style={{ margin: 8 }}>
                    <Title level={5}>汇总报告</Title>
                  </div>
                  <div
                    style={{
                      flex: 1,
                      minHeight: 0,
                      position: "relative",
                      margin: 0,
                      padding: 0,
                    }}
                  >
                    <Table
                      dataSource={excelData}
                      columns={excelColumns}
                      pagination={false}
                      rowKey={(row) => row.key}
                      bordered={true}
                      scroll={{ x: "max-content", y: 300 }}
                      style={{ width: "100%", height: "100%", minHeight: 0 }}
                      title={() => "数据预览"}
                    />
                  </div>
                  <Button
                    icon={<DownloadOutlined />}
                    style={{
                      height: 48,
                      width: 120,
                      fontSize: 18,
                      alignSelf: "flex-end",
                      margin: 16,
                    }}
                    onClick={handleDownload}
                  >
                    下载
                  </Button>
                </>
              )}
            </div>
          </Col>
        </Row>
      </Content>
    </Layout>
  );
};

export default SummaryForSeaTransportation;
